package master.system.organization;

import master.common.data.TreeJSON;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 */
@Controller
@RequestMapping("/organization")
public class OrganizationController {

    @Autowired
    OrganizationService organizationService;

    @RequestMapping("/organization_tree.do")
    @ResponseBody
    public String getOrganizationTree(){
        JSONObject companyJSON = organizationService.getCompany().toJSONObject();
        List<Department> departmentList = organizationService.getDepartments();
        JSONArray departmentJSONArray = TreeJSON.fromListOfObject(departmentList, new TreeJSON.Callback() {
            public void updateJSON(final JSONObject json) {
                if((Boolean)json.get("leaf")) {
                    json.put("icon", "images/icon/picture_empty2.png");
                }
                else {
                    json.put("icon", "images/icon/pictures.png");
                }
            }
        });
        companyJSON.put("text", companyJSON.get("name"));
        companyJSON.put("leaf", false);
        companyJSON.put("expanded", true);
        companyJSON.put("icon", "images/icon/chart_organisation.png");
        companyJSON.put("children", departmentJSONArray);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(companyJSON);
        return jsonArray.toJSONString();
    }

    @RequestMapping("/get_company.do")
    @ResponseBody
    public String getCompany(){
        JSONObject json = organizationService.getCompany().toJSONObject();
        return json.toJSONString();
    }

    @RequestMapping("/department_list.do")
    @ResponseBody
    public String departmentList() {
        return getCompany();
    }

    public static void main(String[] args) {

    }
}
